﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Card.Common
{
    public class LoginUtility
    {
        /// <summary>
        /// 自动登录用户
        /// </summary>
        /// <param name="passport">当前passport</param>
        public static void AutoLogin(Security.Passport passport)
        {
            string strAutoLoginIdentity = Security.CookieManager.GetCookie(CONST.CookieNames.AutoLoginIdentity);

            //如果当前没有用户登录，且客户端存在自动登录cookie认证信息
            if (!passport.IsLogin && !string.IsNullOrEmpty(strAutoLoginIdentity))
            {
                try
                {
                    string[] arrIdentitys = Security.Utility.DecryptString(strAutoLoginIdentity).Split(';');
                    if (arrIdentitys.Length > 0)
                    {
                        string lastSessionId = arrIdentitys[0];

                        int userID = int.Parse(arrIdentitys[1]);
                        Entity.Users user = BLL.UsersManager.GetEntity(userID, passport);
                        //cookie中上次记录lastloginip和数据库中记录相等
                        if (string.Compare(lastSessionId, user.LastSessionID, true) == 0)
                        {
                            passport.UserID = user.ID;
                            passport.UserName = user.UserName;
                            
                            Security.CookieManager.AddPassportCookie(passport);
                            Security.CookieManager.AddCookie(CONST.CookieNames.UName, user.UserName);

                            string sessionId = System.Guid.NewGuid().ToString();//创建登录标识

                            string strIdentity = Security.Utility.EncryptString(string.Format("{0};{1}", sessionId, user.ID));

                            Security.CookieManager.AddCookie(CONST.CookieNames.AutoLoginIdentity, strIdentity, 30);
                            //记录最后登录信息
                            user.LastLoginDate = DateTime.Now;
                            user.LastLoginIp = HttpContext.Current.Request.UserHostAddress;
                            user.LoginCount = user.LoginCount + 1;
                            user.LastSessionID = sessionId;
                            BLL.UsersManager.Update(user, passport);                     
                        }
                    }
                    Common.CardWebUtility.SetCartInfo(passport.UserID);

                }
                catch (Exception ex)
                {
                    Security.CookieManager.RemoveCookie(CONST.CookieNames.AutoLoginIdentity);
                    Log.Logger.Error(ex.ToString());
                }
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="autoLogin">是否设定自动登录</param>
        /// <param name="msg">消息</param>
        /// <param name="passport">当前passport</param>
        /// <returns></returns>
        public static bool Login(string input, string password, bool autoLogin, ref string msg, Security.Passport passport)
        {
            Entity.Users user = BLL.UsersManager.GetUserByUName(input, passport);

            if (user == null)
            {
                msg = "用户不存在！";
            }
            else if (!Security.Utility.ValidatePassword(user.Password, password))
            {
                msg = "密码错误！";
            }
            else
            {
                passport.UserID = user.ID;
                passport.UserName = user.UserName;

                Security.CookieManager.AddCookie(CONST.CookieNames.UName, user.UserName);
                Security.CookieManager.AddPassportCookie(passport);


                string sessionId = System.Guid.NewGuid().ToString();//创建登录标识
                string strIdentity = Security.Utility.EncryptString(string.Format("{0};{1}", sessionId, user.ID));

                //记录最后登录信息
                user.LastLoginDate = DateTime.Now;
                user.LastLoginIp = HttpContext.Current.Request.UserHostAddress;
                user.LoginCount = user.LoginCount + 1;
                user.LastSessionID = sessionId;
                BLL.UsersManager.Update(user, passport);

                if (autoLogin)
                {
                    Security.CookieManager.AddCookie(CONST.CookieNames.AutoLoginIdentity, strIdentity, 30);
                }
                Common.CardWebUtility.SetCartInfo(passport.UserID);
                msg = "登录成功！";
                return true;
            }
            return false;
        }

        /// <summary>
        /// 清除登录认证信息
        /// </summary>
        public static void ClearLoginIdentity()
        {
            Security.CookieManager.RemovePassport();
            Security.CookieManager.RemoveCookie(CONST.CookieNames.AutoLoginIdentity);
            Security.CookieManager.RemoveCookie(CONST.CookieNames.UName);
            Security.CookieManager.AddCookie(CONST.CookieNames.AutoLoginIdentity, string.Empty);
            Security.CookieManager.AddPassportCookie(new Security.Passport());
            Security.CookieManager.AddCookie(CONST.CookieNames.UName,string.Empty);
        }
    }
}
